package com.example.test9;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity2 extends AppCompatActivity {

    private MyDatabaseHelper dbHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }

//    查询表内数据，并将数据存储到集合中

    public List<Contacts> selectContacts(){
        List<Contacts> contacts = new ArrayList<Contacts>();
        dbHelper = new MyDatabaseHelper(this,"Contacts.db",null,2);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("Contacts",new String[]{"Contacts.*"},null,null,null,null,null);
        if(cursor.moveToFirst()){
            do{
//                遍历cursor对象，取出数据
                Contacts contact = new Contacts();
                @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("name"));
                @SuppressLint("Range") int number = cursor.getInt(cursor.getColumnIndex("number"));
                @SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex("id"));

                @SuppressLint("Range") String gender = cursor.getString(cursor.getColumnIndex("gender"));
                contact.setId(id);
                contact.setName(name);
                contact.setNumber(number);
                contact.setGender(gender);

                contacts.add(contact);


            }while(cursor.moveToNext());
        }
        cursor.close();
        return contacts;
    }

    protected void onResume() {
        setContentView(R.layout.activity_main2);
        super.onResume();

        List<Contacts> contacts = selectContacts();
        ListView contactsView = (ListView) findViewById(R.id.contacts_view);
        contactsView.setAdapter(new ContactsAdapter(contacts,this));


    }
}